<?php

namespace App\Http\Controllers;

use App\Http\Requests\StoreMenuRequest;
use App\Http\Requests\UpdateMenuRequest;
use App\Models\Menu;
use Illuminate\Http\Request;

class MenuController extends Controller
{

    public function __construct()
    {
        $this->middleware('auth:sanctum');
    }


    /**
     * Display a listing of the resource.
     */
    public function index(Request $request, Menu $menu)
    {
        $this->authorize('viewAny', $menu);
        $menuAll = $menu->orderBy('order')->get();
        $menusData = $this->dataTree($menuAll, null);
        return $this->success('查询成功', $menusData);
    }

    public function options(Request $request, Menu $menu)
    {
        function changeData($data, $pid)
        {
            $branch = [];
            foreach ($data as $item) {
                if ($item->menus_id == $pid) {
                    $children = changeData($data, $item->id);
                    $newdata = [];
                    if ($children) {
                        $newdata['children'] = $children;
                    }
                    $newdata['label'] = $item->title;
                    $newdata['value'] = $item->id;
                    $branch[] = $newdata;
                }
            }
            return $branch;
        }

        $menuData = $menu->all();
        $menus = changeData($menuData, null);
        return $this->success('查询成功', $menus);
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(StoreMenuRequest $request, Menu $menu)
    {
        $this->authorize('create', $menu);
        $menu->fill($request->input());
        $menu->save();
        return $this->success('新增成功', $menu);
        //
    }

    /**
     * Display the specified resource.
     */
    public function show(Menu $menu)
    {
        $this->authorize('viewAny', $menu);
        return $this->success('请求成功', $menu->toArray());
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(Menu $menu)
    {
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(UpdateMenuRequest $request, Menu $menu)
    {
        //
        $this->authorize('update', $menu);
        $menu->fill($request->input());
        $menu->save();
        return $this->success('编辑成功', $menu);
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Menu $menu)
    {
        $this->authorize('delete', $menu);
        $menu->delete();
        return $this->success('删除成功', $menu);
    }
}
